import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:get/get_state_manager/src/simple/get_state.dart';
import 'package:get/get_state_manager/src/simple/get_view.dart';
import 'package:yt_devops/components/expanded_tab_view.dart';
import 'package:yt_devops/components/gaps.dart';
import 'package:yt_devops/components/log_utils.dart';
import 'package:yt_devops/components/text_width.dart';
import 'package:yt_devops/components/yt_text_style.dart';
import 'package:yt_devops/model/device_obj/properties_model.dart';
import 'package:yt_devops/pages/site/site_setting/siet_elec_price_setting/site_mains_elec_detail/keep_aliver_wrapper.dart';
import 'package:yt_devops/pages/site/site_observer_list/views/my_top_tabbar.dart';
import 'package:yt_devops/resources/str_res_keys.dart';
import 'package:yt_devops/styles/styles.dart';
import 'package:yt_devops/utils/func_utils.dart';

import '../new_air_cooling_page_controller.dart';

///
/// @Description TODO
/// @Author liuer
/// @CreateTime 2024年01月12日 13:57
class DynamicTabView extends GetView {
  final List list;
  final bool isCanScroll;
  num? maxWidth;
  DynamicTabView(this.list,
      {this.isCanScroll = true, this.maxWidth, super.key});

  @override
  Widget build(BuildContext context) {
    maxWidth = maxWidth ?? ScreenUtil().screenWidth - 32;
    return GetBuilder<NewAirCoolingPageController>(
        builder: (_) => ListView.builder(
              shrinkWrap: true,
              physics:
                  isCanScroll ? null : const NeverScrollableScrollPhysics(),
              padding: EdgeInsets.zero,
              itemBuilder: (BuildContext context, int index) {
                return _itemWidget(index, list);
              },
              itemCount: list.length,
            ));
  }

  _itemWidget(int index, List list, {bool isTabView = false}) {
    Map<String, dynamic> map = list[index];

    String title = (map['name'] ?? '').toString();
    String id = (map['id'] ?? '').toString();

    // if(map['value'] == null){
    //   map['value'] = '';
    // }

    PropertiesModel model = PropertiesModel.fromJson(map);
    var realValue = FuncUtils.formatModelValue(map['value'], model.dataType,
            isShowUnit: true)
        .toString()
        .trim();
    Color valueColor = Colour.mainTextColor;
    if (realValue == ResKey.onLine.tr) {
      valueColor = Colour.green;
    } else if (realValue == ResKey.onLine.tr) {
      valueColor = Colour.green;
    } else if (realValue == ResKey.alarm.tr || realValue == ResKey.alarm.tr) {
      valueColor = Colour.warningTextColor;
    } else if (realValue == ResKey.offLine.tr) {
      valueColor = Colour.labelTextColor;
    }

    ///计算title长度 如果内容太长换2行
    double titleW = TextWidth.calculateTextSize(
            title, ytTextStyle(fontSize: 14, color: Colour.otherTextColor)) +
        10.w;
    if (titleW > maxWidth! - 150.w) {
      titleW = maxWidth! - 150.w;
    }
    if (map['type'].toString() == 'tab') {
      return tabView(map);
    } else if (map['type'].toString() == 'group') {
      return groupItem(map);
    } else {
      bool isTopRadius = false;
      bool isBottomRadius = false;
      if (index == 0) {
        if (isTabView) {
          isTopRadius = false;
        } else {
          isTopRadius = true;
        }
      } else if (index == list.length - 1) {
        isBottomRadius = true;
      } else {
        Map<String, dynamic> topMap = list[index - 1];

        if (topMap['name'] == 'margin') {
          isTopRadius = true;
        }
        Map<String, dynamic> bottomMap = list[index + 1];

        if (bottomMap['name'] == 'margin') {
          isBottomRadius = true;
        }
      }
      if (id.toString() == 'mpswiss-${map['deviceId']}') {
        List<dynamic> valueList =
            map['value'] == '--' ? [] : jsonDecode(map['value']);
        List<dynamic> showList = [];
        if (valueList != null && valueList.isNotEmpty) {
          for (int i = 0; i < valueList.length; i++) {
            var name1 = getPowerSwitchName(map, true);
            var name2 = getPowerSwitchName(map, false);
            var unitMap1 = getPowerSwitchUnit(map, true);
            var unitMap2 = getPowerSwitchUnit(map, false);
            var element = valueList[i];
            if (element != null && element is Map) {
              var showElement1 = {
                'name': name1 + (i + 1).toString(),
                'value': unitMap1[element['mposfeed'].toString()].toString()
              };
              var showElement2 = {
                'name': name2 + (i + 1).toString(),
                'value': unitMap2[element['mposfeed'].toString()].toString()
              };
              showList.add(showElement1);
              showList.add(showElement2);
            }
          }
        }
        return GetBuilder<NewAirCoolingPageController>(
          builder: (controller) => KeepAliveWrapper(
            ListView.builder(
              shrinkWrap: true,
              physics: const NeverScrollableScrollPhysics(),
              itemBuilder: (context, index) {
                var element = showList[index];
                String title = element['name'].toString();
                return _itemRowWidget(title, element['value'].toString(), 200.w,
                    Colour.mainTextColor);
              },
              itemCount: showList.length,
            ),
          ),
        );
      } else {
        return title == "margin"
            ? //如果title是margin则说明需要加分割线,为了美观
            Container(
                height: 10,
                color: Colour.backgroundColor,
              )
            : _itemRowWidget(title, realValue, titleW, valueColor,
                isTopRadius: isTopRadius, isBottomRadius: isBottomRadius);
      }
    }
  }

  _itemRowWidget(
    String title,
    String realValue,
    double titleW,
    Color valueColor, {
    bool isTopRadius = false,
    bool isBottomRadius = false,
  }) {
    return Container(
      margin: const EdgeInsets.only(left: 16, right: 16),
      clipBehavior: Clip.hardEdge,
      decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.only(
            topLeft: !isTopRadius ? Radius.zero : const Radius.circular(8),
            topRight: !isTopRadius ? Radius.zero : Radius.circular(8),
            bottomLeft: !isBottomRadius ? Radius.zero : Radius.circular(8),
            bottomRight: !isBottomRadius ? Radius.zero : Radius.circular(8),
          )),
      alignment: Alignment.centerLeft,
      height: 50,
      child: Column(
        children: [
          SizedBox(
            height: 49,
            width: maxWidth?.toDouble(),
            child: Row(
              children: [
                Gaps.hGap16,
                Expanded(
                  child: Container(
                    width: 150,
                    child: Text(
                      title,
                      maxLines: 2,
                      style: ytTextStyle(
                          fontSize: 14, color: Colour.otherTextColor),
                    ),
                  ),
                ),
                Container(
                  width: maxWidth! - titleW - 32.w,
                  alignment: Alignment.centerRight,
                  child: Text(
                    realValue,
                    textAlign: TextAlign.end,
                    maxLines: 2,
                    style: ytTextStyle(fontSize: 14, color: valueColor),
                  ),
                ),
                Gaps.hGap16,
              ],
            ),
          ),
          Visibility(
              visible: !isBottomRadius,
              child: Container(
                margin: EdgeInsets.only(left: 16.w, right: 16.w),
                height: 1,
                color: Colour.backgroundColor,
              ))
        ],
      ),
    );
  }

  Widget groupItem(Map<String, dynamic> map) {
    // Log.d('map===' + map.toString());

    List _list = map['children'];
    Log.d('map===' + map.toString());
    Log.d('_list===' + _list.length.toString());
    return GetBuilder<NewAirCoolingPageController>(
        builder: (controller) => KeepAliveWrapper(Container(
              color: Colour.backgroundColor,
              child: Column(
                children: [
                  Visibility(
                      visible:
                          map['showType'].toString() != '1', //showType==1就需要隐藏
                      child: Container(
                        margin: const EdgeInsets.only(left: 16, right: 16),
                        decoration: const BoxDecoration(
                            color: Colour.white,
                            borderRadius: BorderRadius.all(Radius.circular(8))),
                        height: 49,
                        child: Row(
                          children: [
                            Gaps.hGap16,
                            Text(
                              map['name'].toString(),
                              style: ytTextStyle(
                                  fontSize: 16,
                                  fontWeight: FontWeight.w500,
                                  color: Colour.mainTextColor),
                            ),
                            const Spacer(),
                            Visibility(
                                child: GestureDetector(
                              onTap: () {
                                if (map['isExpand'] == '0') {
                                  map['isExpand'] = '1';
                                } else {
                                  map['isExpand'] = '0';
                                }
                                controller.update();
                              },
                              child: map['isExpand'] == '1'
                                  ? Image.asset(
                                      'assets/images/icon_expand_less.png')
                                  : Image.asset(
                                      'assets/images/icon_expand_more.png'),
                            )),
                            Gaps.hGap16,
                          ],
                        ),
                      )),
                  Visibility(
                      child: Container(
                    height: 0.5,
                    color: Colour.dividerColor,
                    margin: EdgeInsets.only(left: 16.w, right: 16.w),
                  )),
                  Container(
                    height: map['isExpand'] == '1' ? _list.length * 50 : 0,
                    child: ListView.builder(
                      shrinkWrap: true,
                      physics: const NeverScrollableScrollPhysics(),
                      itemBuilder: (context, index) =>
                          _itemWidget(index, _list),
                      itemCount: map['isExpand'] == '1' ? _list.length : 0,
                    ),
                  ),
                  Gaps.vGap10
                ],
              ),
            )));
  }

  Widget tabView(Map<String, dynamic> map) {
    List<dynamic> childrenList = map['children'] ?? [];
    List<String> tabs =
        childrenList.map((e) => e['name'].toString() ?? '').toList();
    var controller = Get.put(NewAirCoolingPageController());
    // Log.d('map=' + map.toString());
    // Log.d('childrenList[0]=' + childrenList[0].toString());
    var tabController = controller.getTabController(tabs.length);
    return Column(
      children: [
        Container(
          width: double.infinity,
          color: Colors.white,
          alignment: Alignment.center,
          padding: EdgeInsets.symmetric(horizontal: 16.w),
          margin: const EdgeInsets.only(left: 16, right: 16),
          child: MyTopTabBar(
            tabController,
            tabs,
          ),
        ),
        ExtendedTabBarView(
          controller: tabController,
          children: childrenList.map(
            (map) {
              if (FuncUtils.isListEmpty(childrenList)) {
                return Gaps.empty;
              } else {
                Log.d('map[]==' + map['children'].toString());
                List<dynamic> tabChildrenList = [];
                if (childrenList != null &&
                    childrenList[0] != null &&
                    childrenList[0]['children'] != null &&
                    childrenList[0]['children']!.isNotEmpty) {
                  tabChildrenList = map['children'][0]['children'];
                }
                Log.d('tabChildrenList=' + tabChildrenList.toString());
                return GetBuilder<NewAirCoolingPageController>(
                  builder: (controller) => KeepAliveWrapper(
                    ListView.builder(
                      shrinkWrap: true,
                      physics: const NeverScrollableScrollPhysics(),
                      itemBuilder: (context, index) =>
                          _itemWidget(index, tabChildrenList, isTabView: true),
                      itemCount: tabChildrenList.length,
                    ),
                  ),
                );
              }
            },
          ).toList(),
        ),
      ],
    );
  }

  ///获取功率开关title
  getPowerSwitchName(Map map, bool isPositive) {
    String title = '';
    if (map != null &&
        map['dataType'] != null &&
        map['dataType']['specs'] != null &&
        map['dataType']['specs']['item'] != null &&
        map['dataType']['specs']['item']['specs'] != null) {
      List temp = map['dataType']['specs']['item']['specs'];
      if (temp != null && temp.length >= 2) {
        if (isPositive) {
          title = temp[0]['name'].toString();
        } else {
          title = temp[1]['name'].toString();
        }
      }
    }
    return title;
  }

  ///获取功率开关真实状态map
  Map getPowerSwitchUnit(Map map, bool isPositive) {
    var returnMap = {};
    if (map != null &&
        map['dataType'] != null &&
        map['dataType']['specs'] != null &&
        map['dataType']['specs']['item'] != null &&
        map['dataType']['specs']['item']['specs'] != null) {
      List temp = map['dataType']['specs']['item']['specs'];
      if (temp != null && temp.length >= 2) {
        if (isPositive) {
          if (temp[0]['dataType'] != null &&
              temp[0]['dataType']['specs'] != null) {
            returnMap = temp[0]['dataType']['specs'];
          }
        } else {
          if (temp[1]['dataType'] != null &&
              temp[1]['dataType']['specs'] != null) {
            returnMap = temp[1]['dataType']['specs'];
          }
        }
      }
    }
    return returnMap;
  }
}
